from info import get_user, g, jsonify, RET, db, current_app
from info.constants import QINIU_DOMIN_PREFIX, OTHER_NEWS_PAGE_MAX_COUNT, USER_COLLECTION_MAX_NEWS, \
    USER_FOLLOWED_MAX_COUNT
from info.models import Category, News, User
from . import user_bp
from flask import render_template, request, session
from info.utility.qiniuyun.qiniu_push import push


@user_bp.route('/')
@get_user
def user_1():
    user = g.user
    data = {
        'user_info': user.to_dict() if user else None
    }
    return render_template('news/user.html', data=data)


@user_bp.route('/user_info', methods=['GET', 'POST'])
@get_user
def user_2():
    user = g.user

    if request.method == 'GET':
        data = {
            'user_info': user.to_dict() if user else None
        }
        return render_template('news/user_base_info.html', data=data)

    if request.method == 'POST':
        nick_name = request.json.get('nick_name')
        signature = request.json.get('signature')
        gender = request.json.get('gender')
        if not all([nick_name, signature, gender]):
            return jsonify(errno=RET.PARAMERR, errmsg='参数不足')
        if gender not in ['MAN', 'WOMAN']:
            return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
        user.nick_name = nick_name
        user.signature = signature
        user.gender = gender
        session['nick_name'] = nick_name
        try:
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="数据库提交错误")
        return jsonify(errno=RET.OK, errmsg="用户信息修改成功")


@user_bp.route('/push_avatar', methods=['GET', 'POST'])
@get_user
def push_avatar():
    user = g.user
    if request.method == 'GET':
        # avatar_url =
        data = {
            'avatar_url': QINIU_DOMIN_PREFIX + user.avatar_url if user.avatar_url else None
        }
        return render_template('news/user_pic_info.html', data=data)
    elif request.method == 'POST':
        avatar = request.files.get('avatar')
        if not all([avatar, user]):
            return jsonify(errno=RET.NODATA, errmsg='未登陆或未选择文件!')
        try:
            avatar_data = avatar.read()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DATAERR, errmsg="数据错误")
        try:
            avatar_key = push(avatar_data)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.THIRDERR, errmsg="图片上传七牛云失败")
        user.avatar_url = avatar_key
        try:
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="数据库添加头像错误")
        full_url = QINIU_DOMIN_PREFIX + avatar_key
        return jsonify(errno=RET.OK, errmsg='更改头像头像成功', data={'avatar_url': full_url})


@user_bp.route('/password_amend', methods=['GET', 'POST'])
@get_user
def password_amend():
    if request.method == 'GET':
        return render_template('news/user_pass_info.html')
    if request.method == 'POST':
        user = g.user
        old_password = request.json.get('old_password')
        new_password = request.json.get('new_password')
        if not all([old_password, new_password]):
            return jsonify(errno=RET.PARAMERR, errmsg='参数不足')
        if not user:
            return jsonify(errno=RET.NODATA, errmsg='未登陆')
        if not user.check_passowrd(old_password):
            return jsonify(errno=RET.PWDERR, errmsg='密码错误')
        user.password = new_password
        try:
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            db.session.rollback()
            return jsonify(errno=RET.DBERR, errmsg="密码修改错误")
        return jsonify(errno=RET.OK, errmsg='密码修改成功')


@user_bp.route('/news_release', methods=['GET', 'POST'])
@get_user
def news_release():
    if request.method == 'GET':
        try:
            categorys = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")
        category_list = []
        for i in categorys if categorys else []:
            if i.id != 1:
                category_list.append(i.to_dict())
        return render_template('news/user_news_release.html', data=category_list)
    if request.method == 'POST':
        data = request.form
        title = data.get('title')
        cid = data.get('category_id')
        digest = data.get('digest')
        content = data.get('content')
        index_image = request.files.get('index_image')
        user = g.user
        source = '个人发布'
        if not all([title, cid, digest, content, index_image]):
            return jsonify(errno=RET.PARAMERR, errmsg="参数不足")
        if not user:
            return jsonify(errno=RET.SESSIONERR, errmsg="用户未登陆")
        # 上传新闻图像
        try:
            news_image_data = index_image.read()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DATAERR, errmsg="数据错误")
        try:
            news_image_key = push(news_image_data)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.THIRDERR, errmsg="图片上传七牛云失败")
        # 创建新闻对象
        new = News()
        new.title = title
        new.category_id = cid
        new.source = source
        new.digest = digest
        new.content = content
        new.index_image_url = QINIU_DOMIN_PREFIX + news_image_key
        new.user_id = user.id
        new.status = 1
        try:
            db.session.add(new)
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="新闻添加到数据库失败")
        return jsonify(errno=RET.OK, errmsg='添加新闻成功')


@user_bp.route('/news_list', methods=['GET', 'POST'])
@get_user
def news_list():
    # if request.method == 'GET':
    p = request.args.get('p', 1)
    user = g.user
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1
    news_list = []
    current_p = 1
    total_p = 1

    try:
        paginate = user.news_list.order_by(News.create_time.desc()).paginate(p, OTHER_NEWS_PAGE_MAX_COUNT, False)
        news = paginate.items
        current_p = paginate.page
        total_p = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询用户发布的新闻错误')
    for i in news if news else []:
        news_list.append(i.to_review_dict())
    data = {
        'news_list': news_list,
        'current_page': current_p,
        'total_page': total_p
    }
    return render_template('news/user_news_list.html', data=data)


@user_bp.route('/collection')
@get_user
def user_collection():
    # 获取页数
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    user = g.user
    collections = []
    current_page = 1
    total_page = 1
    try:
        # 进行分页数据查询
        paginate = user.collection_news.paginate(p, USER_COLLECTION_MAX_NEWS, False)
        # 获取分页数据
        collections = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    # 收藏列表
    collection_dict_li = []
    for news in collections:
        collection_dict_li.append(news.to_basic_dict())

    data = {"total_page": total_page, "current_page": current_page, "collections": collection_dict_li}
    return render_template('news/user_collection.html', data=data)


@user_bp.route('/user_follow')
@get_user
def user_follow():
    # 获取页数
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    user = g.user

    follows = []
    current_page = 1
    total_page = 1
    try:
        paginate = user.followed.paginate(p, USER_FOLLOWED_MAX_COUNT, False)
        # 获取当前页数据
        follows = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    user_dict_li = []

    for follow_user in follows:
        user_dict_li.append(follow_user.to_dict())
    data = {"users": user_dict_li, "total_page": total_page, "current_page": current_page}
    return render_template('news/user_follow.html', data=data)
